package com.wufeng.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wufeng.dto.ConsultApplyDto;
import com.wufeng.dto.R;
import com.wufeng.entity.ConsultApply;
import com.wufeng.entity.Identity;
import com.wufeng.entity.User;
import com.wufeng.service.ConsultApplyService;
import com.wufeng.service.IdentityService;
import com.wufeng.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 申请记录接口
 */
@RestController
@RequestMapping("/consultapply")
public class ConsultApplyController {

    @Autowired
    private ConsultApplyService consultApplyService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private UserService userService;

    /**
     * 获取申请列表
     *
     * @return
     */
    @GetMapping("/getConsultApplyList")
    public R getConsultApplyList() {
        List<ConsultApply> list = consultApplyService.list();
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        return R.ok(map);
    }

    /**
     * 添加申请
     *
     * @param consultApply
     * @return
     */
    @PostMapping("/addConsultApply")
    public R addConsultApply(@RequestBody ConsultApply consultApply) {

        //先查一下是否有未处理的申请，如果有则不添加
        Integer userId = consultApply.getUserid();
        if (userId == null) {
            return R.error("申请失败！");
        }
        QueryWrapper<ConsultApply> eq = new QueryWrapper<ConsultApply>().
                eq("userId", userId).
                eq("handleStatus", 0);//未处理
        List<ConsultApply> list = consultApplyService.list(eq);
        if (!list.isEmpty()) {
            return R.error("申请处理中，请耐心等待...");
        }


        consultApply.setUploadtime(new Date());
        consultApply.setHandlestatus(0);//未处理
        consultApply.setHandleresult(0);//未处理
        try {
            consultApplyService.save(consultApply);
        } catch (Exception e) {
            return R.error("申请失败！");
        }
        return R.ok("申请成功！");


    }


    /**
     * 根据用户id获取申请记录
     *
     * @return
     */
    @GetMapping("/getApplyListByUserId")
    public R getApplyListByUserId(@RequestParam("userId") Integer userId) {
        QueryWrapper<ConsultApply> qw = new QueryWrapper<>();
        qw.eq("userId", userId);
        qw.orderByAsc("uploadTime");

        List<ConsultApply> list = consultApplyService.list(qw);

        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);

        return R.ok(map);
    }


    /**
     * 根据条件查询出申请列表
     *
     * @param params
     * @return
     */
    @PostMapping("/getConsultApplyListByCondition")
    public R getConsultApplyListByCondition(@RequestBody Map<String, Object> params) throws ParseException {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        if (pageIndex == null || pageSize == null) {
            pageIndex = 1;
            pageSize = 5;
        }
        HashMap<String, Object> map = new HashMap<>();

        String userName = (String) params.get("userName");//申请者用户名
        String start = (String) params.get("startTime");
        String end = (String) params.get("endTime");
        Integer handleResult = (Integer) params.get("handleResult");
        Integer handleStatus = (Integer) params.get("handleStatus");

        List<Integer> ids = userService.getUserIdsByUserName(userName);
        //有查询条件，找不到用户
        if (userName != null && ids.isEmpty()) {
            map.put("list", null);
            return R.ok(map);
        }


        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        Date startTime = null;
        Date endTime = null;
        if (start != null && end != null) {
//            startTime = new Date(start);//开始时间
//            endTime = new Date(end);//结束时间
            startTime = dateFormat.parse(start);
            endTime = dateFormat.parse(end);
        }

        ConsultApply consultApply = new ConsultApply();
        consultApply.setHandleresult(handleResult);//结果
        consultApply.setHandlestatus(handleStatus);//状态

        List<ConsultApply> consultApplyList =
                consultApplyService.getConsultApplyListByCondition(ids, startTime, endTime, consultApply, pageIndex, pageSize);

        //根据id查出所有用户
        List<Integer> userIds = consultApplyList.stream().map(c -> c.getUserid()).collect(Collectors.toList());
        List<User> userList = userService.listByIds(userIds);

        List<ConsultApplyDto> list = consultApplyList.stream().map(ca -> {
            ConsultApplyDto cad = new ConsultApplyDto();
            BeanUtils.copyProperties(ca,cad);
            for (User user : userList) {
                if (ca.getUserid() == user.getUserid()){
                    cad.setAvatar(user.getAvatar());
                    cad.setUsername(user.getUsername());
                    break;
                }
            }
            return cad;
        }).collect(Collectors.toList());

        map.put("list", list);
        return R.ok(map);
    }


    /**
     * 根据条件查出总条数
     *
     * @param params
     * @return
     * @throws ParseException
     */
    @PostMapping("/getApplyCountByCondition")
    public R getApplyCountByCondition(@RequestBody Map<String, Object> params) throws ParseException {
        String userName = (String) params.get("userName");//申请者用户名
        String start = (String) params.get("startTime");
        String end = (String) params.get("endTime");
        Integer handleResult = (Integer) params.get("handleResult");
        Integer handleStatus = (Integer) params.get("handleStatus");
        QueryWrapper<ConsultApply> qw = new QueryWrapper<>();
        Date startTime = null;
        Date endTime = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        HashMap<String, Object> map = new HashMap<>();

        List<Integer> ids = userService.getUserIdsByUserName(userName);
        //有查询条件，找不到用户
        if (userName != null && ids.isEmpty()) {
            map.put("total", 0);
            return R.ok(map);
        }

        if (userName != null && !ids.isEmpty()) {
            qw.in("userId", ids);
        }

        if (start != null && end != null) {
//            startTime = new Date(start);//开始时间
//            endTime = new Date(end);//结束时间
            startTime = dateFormat.parse(start);
            endTime = dateFormat.parse(end);
            qw.between("uploadTime", startTime, endTime);
        }

        if (handleStatus != null) {
            qw.eq("handleStatus", handleStatus);
        }
        if (handleResult != null) {
            qw.eq("handleResult", handleResult);
        }


        long count = consultApplyService.count(qw);

        map.put("total", count);

        return R.ok(map);

    }

    /**
     * 处理申请记录，并按条件是否添加身份信息
     *
     * @param consultApply
     * @return
     */
    @Transactional
    @PostMapping("/updateConsultApplyResult")
    public R updateConsultApplyResult(@RequestBody ConsultApply consultApply) {

        System.out.println(consultApply);
//        try {
//
//        }catch (Exception e){
//            return R.error("失败");
//        }
        //修改记录
        consultApply.setHandlestatus(1);
        consultApplyService.updateById(consultApply);
        Identity identity = new Identity();
        //申请通过
        if (consultApply.getHandleresult() == 1) {
            //添加身份信息
            BeanUtils.copyProperties(consultApply, identity);
            System.out.println(identity);
            identityService.saveOrUpdate(identity);
        }
        return R.ok("成功");
    }
}
